package com.linkage.educloud.ah.view.activity.classspace;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.linkage.educloud.ah.Constants;
import com.linkage.educloud.ah.R;
import com.linkage.educloud.ah.adapter.dynamic.DynamicCommentAdapter;
import com.linkage.educloud.ah.adapter.dynamic.DynamicImageListAdapter;
import com.linkage.educloud.ah.bean.AccountData;
import com.linkage.educloud.ah.bean.DynamicBean;
import com.linkage.educloud.ah.bean.DynamicImageBean;
import com.linkage.educloud.ah.bean.PicItem;
import com.linkage.educloud.ah.config.AccountConfig;
import com.linkage.educloud.ah.evenbus.DynamicEvent;
import com.linkage.educloud.ah.mvp.contract.dynamic.IDynamicDetailContract;
import com.linkage.educloud.ah.mvp.contract.dynamic.IDynamicListContract;
import com.linkage.educloud.ah.mvp.presenter.dynamic.DynamicDetailPresenter;
import com.linkage.educloud.ah.mvp.presenter.dynamic.DynamicListPresenter;
import com.linkage.educloud.ah.util.ImageLoader;
import com.linkage.educloud.ah.view.BasicTitleActivity;
import com.linkage.educloud.ah.view.activity.big_picture.BigPictureActivity;
import com.linkage.educloud.ah.widget.CommonDialog;
import com.linkage.educloud.ah.widget.ExpressionUtils;
import com.linkage.educloud.ah.widget.PanelView;
import com.zzhou.common.library.util.LogUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Mr'Tang on 2018/11/20.
 */

public class DynamicDetailActivity extends BasicTitleActivity implements IDynamicDetailContract.IView {

    @BindView(R.id.all_view)
    ScrollView all_view;
    @BindView(R.id.ac_cs_avatar)
    CircleImageView cs_avatar;//圆形头像
    @BindView(R.id.ac_cs_name)
    TextView cs_name;//名字
    @BindView(R.id.ac_cs_role_person)
    ImageView cs_role_person; //教师头衔
    @BindView(R.id.ac_cs_role_teacher)
    ImageView cs_role_teacher;//教师头衔
    @BindView(R.id.ac_cs_time)
    TextView cs_time;//时间
    @BindView(R.id.ac_cs_delete)
    ImageView cs_delete;//本人的动态删除按钮
    @BindView(R.id.ac_cs_rel_content)
    RelativeLayout cs_rel_content;//文字布局
    @BindView(R.id.ac_cs_content_text)
    TextView cs_content_text;//文字
    @BindView(R.id.ac_cs_rel_image)
    RelativeLayout cs_rel_image;//图片布局
    @BindView(R.id.ac_cs_image_oneview)
    ImageView cs_image_oneview;//只有一张图片
    @BindView(R.id.ac_cs_image_gridview)
    GridView cs_image_gridview;//图片gridview
    @BindView(R.id.ac_cs_rel_voice)
    RelativeLayout cs_rel_voice;//声音布局
    @BindView(R.id.ac_cs_voice)
    ImageView cs_voice;//声音图标
    @BindView(R.id.ac_cs_image_intrude)
    TextView cs_image_intrude;//图片介绍
    @BindView(R.id.ac_cs_lin_comment)
    LinearLayout cs_lin_comment;//评论布局
    @BindView(R.id.ac_cs_comment_num)
    TextView cs_comment_num;//评论数量
    @BindView(R.id.ac_cs_lin_praised)
    LinearLayout cs_lin_praised;//赞布局
    @BindView(R.id.ac_cs_priased)
    ImageView cs_priased;//赞图标
    @BindView(R.id.ac_cs_priased_num)
    TextView cs_priased_num;//赞数量
    @BindView(R.id.ac_cs_priased_text)
    TextView cs_priased_text;//赞的具体人
    @BindView(R.id.ac_cs_comment_list)
    ListView cs_comment_list;//评论具体listview

    @BindView(R.id.ac_cs_scroll)
    ScrollView ac_cs_scroll;
    @BindView(R.id.ac_cs_panel)
    PanelView ac_cs_panel;

    private static String KEY_BEAN = "bean";
    private static String KEY_POS = "pos";
    private static String KEY_CLASSID = "classid";
    private DynamicBean dynamic;
    private AccountData accountData;
    private IDynamicDetailContract.IPresenter iPresenter;
    DynamicCommentAdapter commentAdapter;

    public static void launch(Context context, List<DynamicBean> bean, int pos, String class_id) {
        Intent intent = new Intent(context, DynamicDetailActivity.class);
        intent.putExtra(KEY_BEAN, (Serializable) bean);
        intent.putExtra(KEY_POS, pos);
        intent.putExtra(KEY_CLASSID, class_id);
        context.startActivity(intent);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_dynamic_detail;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        iPresenter = new DynamicDetailPresenter(this, this);
        accountData = AccountConfig.getLoginAccount();
        List<DynamicBean> list = (ArrayList<DynamicBean>) getIntent().getSerializableExtra(KEY_BEAN);
        dynamic = list.get(getIntent().getIntExtra(KEY_POS, 0));
        initView();
    }

    private void initView() {
        setTitle("动态详情");
        ac_cs_panel.installView(1, 1, null);
        if (accountData.getUserId() == Long.parseLong(dynamic.getUserid())) {
            cs_delete.setVisibility(View.VISIBLE);
        } else {
            cs_delete.setVisibility(View.GONE);
        }

        cs_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showZloading();
                iPresenter.delDynamics(dynamic.getDynamic_id(), 1, dynamic);
            }
        });

        all_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                ac_cs_scroll.setVisibility(View.GONE);
                ac_cs_panel.clearED();
                return false;
            }
        });

        ImageLoader.loadAvatar(this, Constants.IMAGE_IP_common + dynamic.getAvatar(), cs_avatar);
        cs_time.setText(dynamic.getTime());
        cs_name.setText(dynamic.getName());
        if (dynamic.getRole() == 1) {
            cs_role_person.setVisibility(View.VISIBLE);
            cs_role_teacher.setVisibility(View.VISIBLE);
        } else {
            cs_role_person.setVisibility(View.GONE);
            cs_role_teacher.setVisibility(View.GONE);
        }

        if (dynamic.getContent_type() == 1) {
            cs_rel_content.setVisibility(View.VISIBLE);
            cs_rel_image.setVisibility(View.GONE);
            cs_rel_voice.setVisibility(View.GONE);
            cs_content_text.setText(ExpressionUtils.replaceFace(this,
                    dynamic.getContent()));
        } else if (dynamic.getContent_type() == 2) {
            cs_rel_content.setVisibility(View.VISIBLE);
            cs_rel_image.setVisibility(View.VISIBLE);
            cs_rel_voice.setVisibility(View.GONE);
            cs_content_text.setText(ExpressionUtils.replaceFace(this,
                    dynamic.getContent()));
            if (dynamic.getType() == 2 || dynamic.getType() == 4
                    || dynamic.getType() == 5) {
                cs_image_intrude.setVisibility(View.VISIBLE);
                cs_image_intrude.setText("上传了" + dynamic.getImageList().size()
                        + "张照片到《班级相册》");
            } else {
                cs_image_intrude.setVisibility(View.VISIBLE);
                cs_image_intrude.setText("共传了" + dynamic.getImageList().size()
                        + "张照片");
            }

            final ArrayList<PicItem> picList = new ArrayList<PicItem>();
            for (int i = 0; i < dynamic.getImageList().size(); i++) {
                DynamicImageBean image = dynamic.getImageList().get(i);
                String uri = image.getImage().replace(
                        "small", "big");
                PicItem it;
                if (uri.startsWith("http")) {
                    it = new PicItem(uri, i);
                } else {
                    if (dynamic.getType() == 4) {
                        it = new PicItem(
                                Constants.IMAGE_IP_hexiaoxiao + uri, i);
                    } else {
                        it = new PicItem(
                                Constants.IMAGE_IP_common
                                        + uri, i);
                    }
                }
                picList.add(it);
            }

            if (dynamic.getImageList().size() == 1) {
                cs_image_oneview.setVisibility(View.VISIBLE);
                cs_image_gridview.setVisibility(View.GONE);
                final String uri = dynamic.getImageList().get(0).getImage()
                        .replace("small", "big");
                if (uri.startsWith("http")) {
                    ImageLoader.loadImg(this, uri, cs_image_oneview);
                } else {
                    if (dynamic.getType() == 4) {
                        ImageLoader.loadImg(this, Constants.IMAGE_IP_hexiaoxiao + uri, cs_image_oneview);
                    } else {
                        ImageLoader.loadImg(this, Constants.IMAGE_IP_common + uri, cs_image_oneview);
                    }
                }
                cs_image_oneview.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BigPictureActivity.launch(DynamicDetailActivity.this, picList, 0);
                    }
                });
            } else {
                cs_image_oneview.setVisibility(View.GONE);
                cs_image_gridview.setVisibility(View.VISIBLE);
                cs_image_gridview.setSelector(new ColorDrawable(
                        Color.TRANSPARENT));
                cs_image_gridview.setAdapter(new DynamicImageListAdapter(DynamicDetailActivity.this, dynamic
                        .getImageList()));
            }
            cs_image_gridview
                    .setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent,
                                                View view, int pos, long id) {
                            BigPictureActivity.launch(DynamicDetailActivity.this, picList, pos);
                        }
                    });
        } else if (dynamic.getContent_type() == 3) {
            cs_rel_content.setVisibility(View.GONE);
            cs_rel_image.setVisibility(View.GONE);
            cs_rel_voice.setVisibility(View.VISIBLE);
            final String videoUrl = Constants.IMAGE_IP_common
                    + dynamic.getContent();
            //语音播放
            cs_voice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        MediaPlayer mediaPlayer = new MediaPlayer();
                        File file = new File(videoUrl);
                        FileInputStream fis = new FileInputStream(file);
                        mediaPlayer.setDataSource(fis.getFD());
                        mediaPlayer.prepare();
                        mediaPlayer.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        //评论
        cs_comment_num.setText(dynamic.getCommentnum() + "");
        if (dynamic.getCommentnum() != 0) {
            commentAdapter = new DynamicCommentAdapter(DynamicDetailActivity.this,
                    dynamic.getCommentList(), 2);
            cs_comment_list.setVisibility(View.VISIBLE);
            cs_comment_list.setAdapter(commentAdapter);
            //删除自己的评论 点击事件
            commentAdapter.setOnClickListener(new DynamicCommentAdapter.OnClickListener() {
                @Override
                public void onItemClick(final int position) {
                    if (accountData.getUserId() == Long.parseLong(dynamic.getCommentList().get(position).getUser_id())) {
                        final CommonDialog dialog = new CommonDialog(DynamicDetailActivity.this, "选择操作", "删除评论？", "删除", "取消");
                        dialog.setCancelListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                showZloading();
                                iPresenter.delDynamics(dynamic.getCommentList().get(position).getC_id(), 2, dynamic);
                                dialog.dismiss();
                            }
                        });
                        dialog.setOkListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                        dialog.show();
                    }
                }
            });
        } else {
            cs_comment_list.setVisibility(View.GONE);
        }

        //评论接口
        cs_lin_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ac_cs_scroll.setVisibility(View.VISIBLE);
                ac_cs_panel.andFocusable();

                ac_cs_panel.setOnSendClickListener(new PanelView.OnSendClickListener() {
                    @Override
                    public void onSendClick(String text) {
                        showZloading();
                        ac_cs_scroll.setVisibility(View.GONE);
                        ac_cs_panel.clearED();
                        iPresenter.senddynamicmsg(dynamic, getIntent().getStringExtra(KEY_CLASSID), accountData.getUserId(), accountData.getUserType(), text);
                    }
                });
            }
        });

        //点赞
        cs_priased_num.setText(dynamic.getPraisednum() + "");
        if (dynamic.getIspriased() == 0) {
            cs_priased.setImageResource(R.mipmap.ic_praised_on);
        } else {
            cs_priased.setImageResource(R.mipmap.ic_praised_un);
        }
        cs_priased_text.setText(Html.fromHtml(flushPriase(dynamic)));
        //点赞接口
        cs_lin_praised.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showZloading();
                if (dynamic.getIspriased() == -1) {
                    iPresenter.praisedynamicnew(dynamic, getIntent().getStringExtra(KEY_CLASSID), 0);
                } else {
                    iPresenter.praisedynamicnew(dynamic, getIntent().getStringExtra(KEY_CLASSID), -1);
                }
            }
        });
    }

    //加载 点赞 数据样式
    private static String flushPriase(DynamicBean mic) {
        if (mic.getPraisednum() < 10 && mic.getPraisednum() > 0) {
            StringBuffer bf = new StringBuffer();
            for (int a = 0; a < mic.getPriasedList().size(); a++) {
                if (a == mic.getPriasedList().size() - 1) {
                    bf.append(mic.getPriasedList().get(a).getUser_name());
                } else {
                    bf.append(mic.getPriasedList().get(a).getUser_name() + "、");
                }
            }
            return "<font color='#ff0D92DD'>" + bf.toString() + "</font>" + "觉得赞";
        } else if (mic.getPraisednum() >= 10) {
            StringBuffer bf = new StringBuffer();
            for (int a = 0; a < 10; a++) {
                if (a == 9) {
                    bf.append(mic.getPriasedList().get(a).getUser_name());
                } else {
                    bf.append(mic.getPriasedList().get(a).getUser_name() + "、");
                }
            }
            return "<font color='#ff0D92DD'>" + bf.toString() + "</font>" + "等" + mic.getPraisednum() + "人觉得赞";
        } else {
            return "0人觉得赞";
        }
    }

    //点赞回调
    @Override
    public void updatePraise(DynamicBean bean) {
        hideZloading();
        cs_priased_num.setText(bean.getPraisednum() + "");
        if (bean.getIspriased() == 0) {
            cs_priased.setImageResource(R.mipmap.ic_praised_on);
        } else {
            cs_priased.setImageResource(R.mipmap.ic_praised_un);
        }
        cs_priased_text.setText(Html.fromHtml(flushPriase(bean)));

        EventBus.getDefault().post(new DynamicEvent(DynamicEvent.praise, getIntent().getIntExtra(KEY_POS, 0), bean));
    }

    //删除动态回调
    public void deleteDyanmic() {
        hideZloading();
        EventBus.getDefault().post(new DynamicEvent(DynamicEvent.delete_dynamic, getIntent().getIntExtra(KEY_POS, 0), null));
        finish();
    }

    //增加评论回调
    public void changeComment(DynamicBean bean) {
        hideZloading();
        cs_comment_num.setText(bean.getCommentnum() + "");
        if (bean.getCommentnum() != 0) {
            dynamic = bean;
            commentAdapter.notifyDataSetChanged();
            cs_comment_list.setVisibility(View.VISIBLE);
            cs_comment_list.setAdapter(commentAdapter);
        } else {
            cs_comment_list.setVisibility(View.GONE);
        }

        EventBus.getDefault().post(new DynamicEvent(DynamicEvent.delete_comment, getIntent().getIntExtra(KEY_POS, 0), bean));
    }
}